const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')

// error handler
onerror(app)

// mongo db
const mongoose = require('mongoose');
const db = 'mongodb://wanthering:oddbird125@123.57.70.210:27017/audioshare';
mongoose.Promise = require('bluebird');
mongoose.connect(db, {useMongoClient: true});


//auto load models

//文件自动加载=================================================
const fs = require('fs');
const path = require('path');

const models_path = path.join(__dirname,'./routes/models');


//设置遍历函数,自动引入文件内所有的文件。
const walk = function(modelPath){
  fs.readdirSync(modelPath)
    .forEach(function(file){
      const filePath = path.join(modelPath,'/'+file);
      const stat = fs.statSync(filePath);
      if(stat.isFile()){
        if(/(.*)\.(js|coffee)/.test(file)){
          require(filePath);
        }
      }else if(stat.isDirectory()){
        walk(filePath)
      }
    })
};

walk(models_path);
//初始化koa业务逻辑====================================




// middlewares
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'pug'
}))

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`method: ${ctx.method}   ||   url: ${ctx.url}   ||   time used: ${ms}ms`)
})

const index = require('./routes/index')

// const audios = require('./routes/audios')
// routes

app.use(index.routes(), index.allowedMethods())
// app.use(audios.routes(), audios.allowedMethods())

module.exports = app
